package com.gaohc.system.sysuser.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaohc.common.constant.Constants;
import com.gaohc.common.constant.UserConstants;
import com.gaohc.common.core.domain.entity.SysRole;
import com.gaohc.common.core.domain.entity.SysUser;
import com.gaohc.common.core.redis.RedisUtil;
import com.gaohc.common.exception.BusinessException;
import com.gaohc.common.utils.StringUtils;
import com.gaohc.system.sysuser.domain.SysUserRole;
import com.gaohc.system.sysuser.mapper.SysUserMapper;
import com.gaohc.system.sysuser.ISysUserRoleService;
import com.gaohc.system.sysuser.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService
{

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private ISysUserRoleService sysUserRoleService;

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     */
    @Override
    public void updateUserProfile(SysUser user)
    {
        this.updateById(user);
    }

    @Override
    public SysUser getUserInfoById(Long id) {
        String userKey = Constants.LOGIN_TOKEN_KEY + id;
        if (redisUtil.hasKey(userKey)) {
            return (SysUser) redisUtil.get(userKey);
        }
        return this.getById(id);
    }

    @Override
    public void checkUserAllowed(SysUser user) {
        boolean admin = SysUser.isAdmin(user.getUserId());
        if (admin) {
            throw new BusinessException("不允许操作超级管理员用户");
        }
    }

    @Override
    public void insertUserAuth(Long userId, Long[] roleIds) {
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        sysUserRoleService.remove(queryWrapper);
        insertUserRole(userId, roleIds);
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName)
    {
        Long count = lambdaQuery().eq(SysUser::getUserName, userName).count();
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = lambdaQuery().eq(SysUser::getPhonenumber, user.getPhonenumber()).one();
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = lambdaQuery().eq(SysUser::getEmail, user.getEmail()).one();
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public void insertUser(SysUser user) {
        this.save(user);
        // 添加用户、角色关联
        insertUserRole(user.getUserId(), user.getRoleIds());
    }

    private void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotNull(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<>();
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                sysUserRoleService.saveBatch(list);
            }
        }
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean updateUser(SysUser user)
    {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        sysUserRoleService.removeById(userId);
        // 新增用户与角色管理
        insertUserRole(user.getUserId(), user.getRoleIds());
        return this.updateById(user);
    }

    @Override
    public Object selectUserRoleGroup(Long userId) {
        List<SysRole> list = sysUserRoleService.selectRolesByUserId(userId);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    @Override
    public void clearRedisUser(Long id) {
        String userKey = Constants.LOGIN_TOKEN_KEY + id;
        redisUtil.del(userKey);
    }

}
